package com.scisoft.scan.control.quickcheck;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.ScanHelper;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.depot.WarehouseBean;
import com.scisoft.scan.data.quickcheck.QuickCheckDetailBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper;
import com.scisoft.scan.ws.WebServiceHelper_Depot;
import com.scisoft.scan.ws.WebServiceHelper_QuickCheck;

import java.util.ArrayList;
import java.util.List;

public class QuickCheckActivity extends Activity {

    private ImageView iv_Back; //返回按钮
    private ImageView iv_query; //搜索按钮
    private ListView lv_data;
    private Spinner spin_depot;
    private ClearEditText et_bar;
    private TextView tv_submit;

    private String orderId = null;//当前盘点单id，默认为null
    private List<QuickCheckDetailBean> quickCheckDetailBeanList = new ArrayList<>();//盘点单列表
    private List<String> depotList = new ArrayList<>();//仓库名列表
    private List<WarehouseBean> depotBeanList = new ArrayList<WarehouseBean>();//仓库列表
    private int selectedDepotNo = 0;//当前选择的仓库

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_quick_check);

        //控件初始化
        lv_data = findViewById(R.id.lv_data);
        //仓库
        spin_depot = findViewById(R.id.spin_depot);
        et_bar = findViewById(R.id.et_bar);
        et_bar.setText("");
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //审核
        tv_submit = findViewById(R.id.tv_submit);
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (quickCheckDetailBeanList == null || quickCheckDetailBeanList.size() == 0) {
                    Toast.makeText(getApplicationContext(), "盘点单列表不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                if (orderId == null) {
                    Toast.makeText(getApplicationContext(), "盘点单号不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                CommonUtil.showPress(QuickCheckActivity.this);
                AuditTask auditTask = new AuditTask(QuickCheckActivity.this);
                auditTask.execute();
            }
        });
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索配件
                String condition = et_bar.getUpperText().toString();
                //判断是否仓库
                if (selectedDepotNo == 0) {
                    Toast.makeText(getApplicationContext(), "请先选择仓库", Toast.LENGTH_LONG).show();
                    return;
                }
                //跳转
                Intent intent = new Intent(QuickCheckActivity.this, CheckPartQueryActivity.class);
                intent.putExtra("depot", depotBeanList.get(selectedDepotNo));
                intent.putExtra("orderId", orderId);
                intent.putExtra("flag", "1");
                intent.putExtra("condition", condition);
                startActivityForResult(intent, 0);

            }
        });

        CommonUtil.showPress(this);
        QueryWarehouseTask queryTask1 = new QueryWarehouseTask(QuickCheckActivity.this);
        queryTask1.execute();
    }

    //返回当前界面
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //填入配件信息
        if (resultCode == RESULT_OK) {
            orderId = data.getStringExtra("data");
            if (orderId != null) {
                CommonUtil.showPress(this);
                QueryQuickCheckOrderTask queryQuickCheckOrderTask = new QueryQuickCheckOrderTask(QuickCheckActivity.this);
                queryQuickCheckOrderTask.execute();
            }
        }
    }

    //绑定仓库数据
    private void SetSpanDepot(Context context) {
        spin_depot = findViewById(R.id.spin_depot);
        for (int i = 0; i < depotBeanList.size(); i++) {
            depotList.add(depotBeanList.get(i).depotName);
        }
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.style_spinner, depotList);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_depot.setAdapter(adapter2);
        spin_depot.setSelection(0, true);
        spin_depot.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedDepotNo = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //查询仓库服务
    class QueryWarehouseTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryWarehouseTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                depotBeanList = WebServiceHelper_Depot.DEPOT_01();
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                CommonUtil.hidePress();
                SetSpanDepot(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //绑定查询信息
    private void BandData(Context context) {
        //设置适配器
        QuickCheckAdapter adapter = new QuickCheckAdapter(quickCheckDetailBeanList, QuickCheckActivity.this);
        lv_data.setAdapter(adapter);
    }

    //查询仓库服务
    class QueryQuickCheckOrderTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryQuickCheckOrderTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                quickCheckDetailBeanList = WebServiceHelper_QuickCheck.QUICKCHECK_03(orderId);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                CommonUtil.hidePress();
                BandData(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //审核服务
    class AuditTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        AuditTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_QuickCheck.QUICKCHECK_04(orderId);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                Toast.makeText(getApplicationContext(), "提交成功", Toast.LENGTH_LONG).show();
                finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }


    //以下为扫码相关

    //初始化
    private void init(){
        //初始化Profile
        ScanHelper.CreateProfile(this);
        //设置广播消息的接收器
        registerReceiver();
    }

    //查询条码服务
    class QueryBarCodeTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String barCode;
        private BarCodeBean barCodeBean = null;

        QueryBarCodeTask(Context context, String barCode) {
            super();
            mcontext = context;
            this.barCode = barCode;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                barCodeBean = WebServiceHelper.ParseBarCode(barCode);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (barCodeBean == null || barCodeBean.barType == BarCodeBean.BAR_UNKNOWN) {
                    Toast.makeText(QuickCheckActivity.this, "无效二维码：" + barCode, Toast.LENGTH_LONG).show();
                } else if (barCodeBean.barType == BarCodeBean.BAR_PART) {
                    //判断是否仓库
                    if (selectedDepotNo == 0) {
                        Toast.makeText(getApplicationContext(), "请先选择仓库", Toast.LENGTH_LONG).show();
                        return;
                    }
                    //跳转
                    Intent intent = new Intent(QuickCheckActivity.this, CheckPartQueryActivity.class);
                    intent.putExtra("depot", depotBeanList.get(selectedDepotNo));
                    intent.putExtra("orderId", orderId);
                    intent.putExtra("flag", "2");
                    intent.putExtra("part", barCodeBean.partBean);
                    startActivityForResult(intent, 0);
                } else if (barCodeBean.barType == BarCodeBean.BAR_SHELVES) {
                    Toast.makeText(QuickCheckActivity.this, "请扫描配件", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //扫码处理
    private void ScanData(String barCode) throws Exception {
        if (barCode != null && barCode.length() > 0) {
            CommonUtil.showPress(this);
            QueryBarCodeTask queryBarCodeTask = new QueryBarCodeTask(QuickCheckActivity.this, barCode);
            queryBarCodeTask.execute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        //IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        //registerReceiver(mResultReceiver, intFilter);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScanHelper.ACTION_RESULT_NOTIFICATION);   // for notification result
        filter.addAction(ScanHelper.ACTION_RESULT);                // for error code result
        filter.addCategory(Intent.CATEGORY_DEFAULT);    // needed to get version info
        filter.addAction(ScanHelper.ACTION_SCAN_OUTPUT); // register to received broadcasts via DataWedge scanning
        registerReceiver(mResultReceiver, filter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ScanHelper.ACTION_SCAN_OUTPUT)) {
                // 处理扫码结果
                try {
                    String decodedData = intent.getStringExtra("com.symbol.datawedge.data_string");
                    ScanData(decodedData);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(QuickCheckActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };

}
